import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class AddDistributor extends HttpServlet
{
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
	{
		doPost(request,response);
	}//doGet

	public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
	{
		RequestDispatcher dispatcher = null;
		String event = request.getParameter("eventAction");
		if( event.equals("exit") )
		{
			dispatcher = request.getRequestDispatcher("/jsp/OperatorActivities.jsp");
			dispatcher.forward(request,response);
		}
		try
		{
			String msg = "";
			String jspUrl = "";
			String distcode = request.getParameter("distcode");
			String glcode = request.getParameter("glcode");
			String region = request.getParameter("region");
			String district = request.getParameter("district");
			String hub = request.getParameter("hub");
			String address = request.getParameter("address");

			Class.forName("com.mysql.jdbc.Driver").newInstance();
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/airtel","root","root");
			Statement stmt = con.createStatement();
			int id = 0;
			ResultSet rs = stmt.executeQuery("select max(id) from distributor");
			if(rs.next())
			{
				if( rs.getString(1) != null )
				{
					id = Integer.parseInt(rs.getString(1));
				}
			}
			id++;
			rs.close();
			int code = 0;
			rs = stmt.executeQuery(" SELECT code FROM distributor where glcode='"+glcode+"'");
			if( rs.next() == false )
			{ 
				stmt.executeUpdate("insert into distributor values('"+id+"','"+distcode+"','"+glcode+"','"+address+"','"+region+"','"+district+"','"+hub+"')");
				msg = "New Distributor Added with Code "+distcode;
				jspUrl= "/jsp/Distributor.jsp";
				System.out.println("Distributor Added");
			}
			else
			{
				code = rs.getInt(1);
				msg = "Already existed"+code;
				jspUrl = "/jsp/Distributor.jsp";
			}
			request.setAttribute("msg",msg);
			dispatcher = request.getRequestDispatcher(jspUrl);
			dispatcher.forward(request,response);
		}//try
		catch(Exception e)
		{
            e.printStackTrace();
		}//catch
	}//doPost
}//class